﻿namespace Reviewer.Web.UI
{
    using System;
    using System.Reflection;
    using System.Runtime.Serialization;
    using System.Web.UI.WebControls;
    using Reviewer.Entities.MetadataInfo;

    public class MetadataTextPropertyControl : MetadataPropertyControl
    {
        protected TextBox textBox = new TextBox();

        public MetadataTextPropertyControl(PropertyInfo property)
            : base(property)
        {
        }

        protected override void CreateChildControlsEx()
        {
            this.textBox.ID = this.ID + "_tb" + this.propertyInfo.Name;
            this.textBox.ValidationGroup = this.ValidationGroup;
            this.Controls.Add(this.textBox);

            this.label.AssociatedControlID = this.textBox.ID;

            MetadataTextPropertyAttribute textAttribute = Attribute.GetCustomAttribute(this.propertyInfo, typeof(MetadataTextPropertyAttribute)) as MetadataTextPropertyAttribute;
            if (textAttribute.MaxLength > 0)
            {
                this.textBox.MaxLength = textAttribute.MaxLength;
            }

            DataMemberAttribute dataMemberAttribute = Attribute.GetCustomAttribute(this.propertyInfo, typeof(DataMemberAttribute)) as DataMemberAttribute;
            if (dataMemberAttribute.IsRequired)
            {
                RequiredFieldValidator requiredField = new RequiredFieldValidator();
                requiredField.ControlToValidate = this.textBox.ID;
                requiredField.Display = ValidatorDisplay.Dynamic;
                requiredField.ErrorMessage = "<br />Required field";
                requiredField.ValidationGroup = this.ValidationGroup;
                this.Controls.Add(requiredField);
            }
        }

        public override void Reset()
        {
            EnsureChildControls();
            this.textBox.Text = String.Empty;
        }

        public override void SetProperty(object item)
        {
            this.EnsureChildControls();

            this.propertyInfo.SetValue(item, this.textBox.Text, null);
        }

        public override void GetProperty(object item)
        {
            this.EnsureChildControls();

            this.textBox.Text = this.propertyInfo.GetValue(item, null).ToString();
        }

    }
}